import Sortable from 'sortablejs'

export default {
	name: 'jm-draggable',
	props: {
		list: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			instance: null,
			arrData: []
		}
	},
	render(h) {
		return h('div', { ref: 'draggableRef' }, this.$slots.default)
	},
	mounted() {
		this.$nextTick(() => {
			this.init()
		})
	},
	watch: {
		list: {
			handler() {
				this.arrData = this.list
			},
			immediate: true
		}
	},
	methods: {
		init() {
			const dom = this.$refs.draggableRef
			if (dom) {
				this.instance = new Sortable(dom, {
					animation: 150,
					onEnd: e => {
						const tempItem = this.arrData.splice(e.oldIndex, 1).at(0)
						this.arrData.splice(e.newIndex, 0, tempItem)
						this.$emit('update:list', this.arrData)
					}
				})
			}
		}
	}
}
